<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="预约人" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预约手机" prop="mobile" >
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="预约状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
          <el-option label="待报到" :value="0" />
          <el-option label="已完成" :value="1" />
          <el-option label="已取消" :value="2" />
          <el-option label="已过期" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="预约时间" prop="time">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期时间"
          end-placeholder="结束日期时间"
          value-format="YYYY-MM-DDTHH:mm:ss"
          :default-time="[
            new Date(2000, 1, 1, 0, 0, 0),
            new Date(2000, 1, 1, 23, 59, 59),
          ]"
          @change="handleDateRangeChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="全部" name="all" />
      <el-tab-pane label="参观预约" name="0" />
      <el-tab-pane label="探访预约" name="1" />
    </el-tabs>

    <el-row :gutter="10" class="mb8">
      <el-col :span="24" style="text-align: right">
        <el-button
          type="success"
          plain
          icon="Upload"
          @click="handleImport"
          style="margin-left: 8px"
        >导入</el-button>
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          style="margin-left: 8px"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="reservationList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" type="index" width="50" align="center" />
      <el-table-column label="预约类型" align="center" prop="type">
        <template #default="scope">
          {{ scope.row.type == 0 ? '参观预约' : '探访预约' }}
        </template>
      </el-table-column>
      <el-table-column label="预约人姓名" align="center" prop="name" />
      <el-table-column label="预约人手机号" align="center" prop="mobile" />
      <el-table-column label="老人姓名" align="center" prop="visitor" />
      <el-table-column label="预约时间" align="center" prop="time" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.time, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约状态" align="center" prop="status">
        <template #default="scope">
          <el-tag type="warning" v-if="scope.row.status === 0">待报到</el-tag>
          <el-tag type="success" v-if="scope.row.status === 1">已完成</el-tag>
          <el-tag type="danger" v-if="scope.row.status === 2">已取消</el-tag>
          <el-tag type="info" v-if="scope.row.status === 3">已过期</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link :type="scope.row.status == 0 ? 'primary':'info'" @click="handleArrival(scope.row)" :disabled="scope.row.status !== 0">到院</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 到院时间确认弹窗 -->
    <el-dialog title="确认到院时间" v-model="arrivalDialogVisible" width="500px" append-to-body>
      <el-form :model="arrivalForm" ref="arrivalFormRef" :rules="arrivalRules" label-width="80px">
        <el-form-item label="到院时间" prop="arrivalTime">
          <el-date-picker
            v-model="arrivalForm.arrivalTime"
            type="datetime"
            placeholder="请选择到院时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="arrivalDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitArrival">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 添加导入弹窗 -->
    <el-dialog title="导入预约数据" v-model="importDialogVisible" width="500px" append-to-body>
      <el-upload
        ref="uploadRef"
        v-model:file-list="fileList"
        :action="uploadAction"
        :headers="headers"
        accept=".xlsx, .xls"
        :limit="1"
        :auto-upload="false"
        :multiple="false"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="handleBeforeUpload"
        :on-exceed="handleExceed"
      >
        <el-button type="primary">选择文件</el-button>
        <template #tip>
          <div class="el-upload__tip">请上传 Excel 文件（.xlsx, .xls）</div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitUpload" :disabled="fileList.length === 0">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Reservation">
import { listReservation, getReservation, updateReservation } from "@/api/nursing/reservation";
import { getToken } from "@/utils/auth";
import { download } from "@/utils/request";

const { proxy } = getCurrentInstance();
const reservationList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref([]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    mobile: null,
    startTime: null,
    endTime: null,
    visitor: null,
    type: null,
    status: null,
  }
});

const { queryParams } = toRefs(data);

/** 查询预约信息列表 */
function getList() {
  loading.value = true;
  listReservation(queryParams.value).then(response => {
    reservationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 日期范围变化处理
function handleDateRangeChange(val) {
  if (val) {
    queryParams.value.startTime = val[0];
    queryParams.value.endTime = val[1];
  } else {
    queryParams.value.startTime = null;
    queryParams.value.endTime = null;
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

const activeTab = ref('all');

// 标签页点击事件处理
function handleTabClick(tab) {
  if (tab.props.name === 'all') {
    queryParams.value.type = null;
  } else {
    queryParams.value.type = parseInt(tab.props.name);
  }
  handleQuery();
}

// 重置按钮操作
function resetQuery() {
  dateRange.value = [];
  activeTab.value = 'all';
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 到院弹窗相关变量
const arrivalDialogVisible = ref(false);
const arrivalForm = ref({
  id: null,
  arrivalTime: null
});
const arrivalRules = {
  arrivalTime: [
    { required: true, message: "请选择到院时间", trigger: "change" }
  ]
};
const arrivalFormRef = ref(null);

/** 到院操作 */
function handleArrival(row) {
  arrivalForm.value.id = row.id;
  arrivalForm.value.arrivalTime = null;
  arrivalDialogVisible.value = true;
}

/** 提交到院确认 */
function submitArrival() {
  arrivalFormRef.value.validate(valid => {
    if (valid) {
      proxy.$modal.confirm('是否确认到院？').then(function() {
        return updateReservation({
          id: arrivalForm.value.id,
          status: 1,
          time: arrivalForm.value.arrivalTime
        });
      }).then(() => {
        arrivalDialogVisible.value = false;
        getList();
        proxy.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    }
  });
}

/** 取消预约 */
function handleCancel(row) {
  proxy.$modal.confirm('是否确认取消预约？').then(function() {
    return updateReservation({
      id: row.id,
      status: 2
    });
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.$modal.confirm('是否确认导出所有预约数据项?').then(() => {
    proxy.$modal.loading("正在导出数据，请稍候...");
    download('/nursing/reservation/export', {
      ...queryParams.value
    }, `预约数据_${new Date().getTime()}.xlsx`).then(() => {
      proxy.$modal.closeLoading();
      proxy.$modal.msgSuccess("导出成功");
    }).catch(() => {
      proxy.$modal.closeLoading();
    });
  });
}

// 文件上传相关变量
const importDialogVisible = ref(false);
const uploadRef = ref(null);
const fileList = ref([]);
const uploadAction = ref('/dev-api/nursing/reservation/import');

// 上传相关方法
function handleImport() {
  importDialogVisible.value = true;
}

function handleUploadSuccess(response) {
  if (response.code === 200) {
    proxy.$modal.msgSuccess("导入成功");
    importDialogVisible.value = false;
    getList(); // 刷新列表
  } else {
    proxy.$modal.msgError(response.msg || "导入失败");
  }
  uploadRef.value.clearFiles();
}

function handleUploadError() {
  proxy.$modal.msgError("导入失败");
  uploadRef.value.clearFiles();
}

function handleBeforeUpload(file) {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel';
  if (!isExcel) {
    proxy.$modal.msgError('只能上传 Excel 文件！');
    return false;
  }
  return true;
}

function handleExceed() {
  proxy.$modal.msgError('只能上传一个文件！');
}

// 在 script setup 中添加 headers 定义
const headers = {
  Authorization: 'Bearer ' + getToken()
};

// 在 script 部分添加 submitUpload 方法
function submitUpload() {
  if (fileList.value.length === 0) {
    proxy.$modal.msgError("请先选择文件");
    return;
  }
  uploadRef.value.submit();
}

getList();
</script>

<style scoped>
.el-upload__tip {
  color: #909399;
  font-size: 14px;
  margin-top: 7px;
}
</style>
